import type { PickerValue } from 'antd-mobile/es/components/picker-view'
import type { Props as SearcherProps } from '@/components/Common/Searcher/interface'
import type { TrainPlanType } from '../interface'
import type { CascadePickerOption } from 'antd-mobile/es/components/cascade-picker'
import { CascadePicker, Picker } from 'antd-mobile'
import { useLocalObservable, useObserver } from 'mobx-react'
import { fetchDictList } from '@/api/base'
import { useEffect } from 'react'
import Searcher from '@/components/Common/Searcher'

/** 转换成【选择组件】需要的数据格式 */
const transformToColumns = <T extends Record<string, any>>(
    v: T,
    children?: CascadePickerOption[],
) =>
    Object.entries(v).map(([value, label]) => ({
        label: String(label),
        value,
        children,
    }))

const DEFAULT_ALL_OPTION = Object.freeze({ label: '全部', value: '' })

/** 搜索选项 */
const searcherOption = [
    { label: '时间', param: 'time' as const },
    { label: '状态', param: 'state' as const },
]

/** 审核状态选项 */
const stateOptions: { label: string; value: TrainPlanType.CheckState }[] = [
    { label: '待审核', value: 0 },
    { label: '通过', value: 1 },
    { label: '未通过', value: 2 },
]

/** 审核状态PickerColumns */
const stateColumns = [
    [DEFAULT_ALL_OPTION, ...stateOptions.map(item => ({ ...item, value: String(item.value) }))],
] as { label: string; value: string }[][]

export type OnInputFocus = Exclude<
    SearcherProps<typeof searcherOption[0]>['onInputFocus'],
    undefined
>
export type SearcherParam = Parameters<OnInputFocus>[0]

/** 培训计划搜索 */
const PlanSearcher = (props: {
    onSearcher?: (param: SearcherParam, value: PickerValue[]) => any
}) => {
    const store = useLocalObservable(() => ({
        showValue: '' as any,

        timeValue: undefined as undefined | PickerValue[],
        stateValue: undefined as undefined | PickerValue[],

        timeOptions: [] as CascadePickerOption[],
        divisionColumns: [] as CascadePickerOption[],
        yearColumns: [] as CascadePickerOption[],

        async fetchOptionsToStore() {
            const [divisionOptions, yearOptions] = await fetchDictList(['division', 'dec_year'])

            // 上半年/下半年
            const divisionColumns = [DEFAULT_ALL_OPTION, ...transformToColumns(divisionOptions)]
            // 年份
            const yearColumns = [
                DEFAULT_ALL_OPTION,
                ...transformToColumns(yearOptions, divisionColumns),
            ]

            store.yearColumns = yearColumns
            store.divisionColumns = divisionColumns
            store.timeOptions = yearColumns
        },
    }))

    useEffect(() => {
        store.fetchOptionsToStore()
    }, [store])

    /** picker确认选择 */
    const onPickerConfirm = (param: SearcherParam, value: { label: string; value: string }[]) => {
        if (!value) return

        /** 抛出的值 */
        props.onSearcher?.(
            param,
            value.map(item => item.value),
        )
    }

    return useObserver(() => {
        const onInputFocus: OnInputFocus = async param => {
            switch (param) {
                case 'time': {
                    await CascadePicker.prompt({
                        defaultValue: store.timeValue,
                        options: store.timeOptions,
                        onConfirm: pickerValue => {
                            const [year, division] = pickerValue

                            const yearSelected = store.yearColumns.find(item => item.value === year)
                            const divisionSelected = store.divisionColumns.find(
                                item => item.value === division,
                            )
                            const selected = [yearSelected!, divisionSelected!].filter(v => v)

                            /** 回显值 */
                            store.showValue = selected.map(item => item.label).join('-')
                            store.timeValue = pickerValue

                            onPickerConfirm(param, selected)
                        },
                    })
                    break
                }

                case 'state': {
                    Picker.prompt({
                        defaultValue: store.stateValue,
                        columns: stateColumns,
                        onConfirm: pickerValue => {
                            const [state] = pickerValue

                            const stateSelected = stateColumns[0].find(item => item.value === state)
                            const selected = [stateSelected!].filter(v => v)

                            /** 回显值 */
                            store.showValue = stateSelected!.label
                            store.stateValue = pickerValue

                            onPickerConfirm(param, selected)
                        },
                    })
                    break
                }
            }
        }

        return (
            <Searcher
                value={store.showValue}
                options={searcherOption}
                /** 切换搜索类型时，重置搜索条件。并重新请求。 */
                onParamChange={param => {
                    onPickerConfirm(param, [])
                }}
                onInputFocus={onInputFocus}
            />
        )
    })
}

export default PlanSearcher
